package fr.emse.tatiana.commands;


import java.io.File;
import java.util.List;


import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.IWorkbenchWindow;
import fr.emse.tatiana.CorpusNavigationView;
import fr.emse.tatiana.corpus.Corpus;






public class RenameFileAction extends Action{
	private final IWorkbenchWindow window;
	private final String viewId;

	private static RenameFileAction instance;

	public static RenameFileAction getInstance() {
		return instance;
	}

	public RenameFileAction(IWorkbenchWindow window, String label, String id) {
		this.window = window;
		this.viewId = id;
		setText(label);
		setId(ICommandIds.CMD_RENAME_FILE);
		//setImageDescriptor(fr.emse.tatiana.Activator.getImageDescriptor("/icons/sample2.gif"));
		this.setEnabled(false);
		instance = this;
	}



	public void run() {
		
		IStructuredSelection sel=((CorpusNavigationView) window.getActivePage().findView(this.viewId)).getSelection();
		IResource res = ((IResource) sel.getFirstElement());
	
		if (res instanceof IProject) {
			MessageDialog.openError(window.getShell(),"Error","You can't rename a project");
			return;
		}
	
		
		if(window != null) {	
			InputDialog dialog = new InputDialog(window.getShell(), 
					"Rename", 
					"New name of the file", null, null); 
			if (dialog.open() != Window.OK)
				return;
			
			
			IPath source = res.getFullPath();
			String oldname = source.lastSegment();
			String newname = dialog.getValue();
			IPath dest = source.removeLastSegments(1).append(newname);
			try {
				res.move(dest, false, null);
			} catch (CoreException e) {
				MessageDialog.openError(window.getShell(),"Error","The file can't be renamed");
				return;
			}
			if (res instanceof IFile) {
				List<IResource> hidden = Corpus.getAssociatedHiddenFiles((IFile) res);
				for (IResource hid: hidden) {
					source = hid.getFullPath();
					dest = source.removeLastSegments(1).append(source.lastSegment().replace(oldname, newname));
					try {
						hid.move(dest, false, null);
					} catch (CoreException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}

		}
	}
}



